<template>
  <div><h1>问卷调查</h1></div>
  <myinput
    v-for="inp in inputs"
    :key="inp.id"
    :title="inp.title"
    :required="inp.required"
    :value="recoveryResult(inp.title, `input${inp.id}`, inp.required) || ''"
    :validator="validateResult[`input${inp.id}`] || init"
    @select="getValue($event, inp.title, `input${inp.id}`, inp.required)"
  />
  <myradio
    v-for="radio in radios"
    :key="radio.id"
    :title="radio.title"
    :itemData="radio.items"
    :required="radio.required"
    :value="
      recoveryResult(radio.title, `radio${radio.id}`, radio.required) || ''
    "
    :validator="validateResult[`radio${radio.id}`] || init"
    @select="getValue($event, radio.title, `radio${radio.id}`, radio.required)"
  />
  <div style="text-align: center">
    <el-button type="primary" @click="submit">提交</el-button>
    <el-button type="success" @click="save">保存</el-button>
  </div>
</template>

<script>
import Vote from "./Vote.vue";
import myradio from "./myradio.vue";
import myinput from "./myinput.vue";
import http from "./api/http";
import { reactive, toRefs, computed } from "vue";
import { ElButton } from "element-plus";
import { useRouter } from "vue-router";
import api from "./api";
import store from "./store";

export default {
  name: "App",
  components: {
    Vote,
    myradio,
    myinput,
    ElButton,
  },
  setup() {
    const state = reactive({
      data: [],
      radios: [],
      checks: [],
      inputs: [],
      stars: [],
      validateResult: {},
      init: true,
    });

    http.get("/data.json").then((res) => {
      state.data = res.data;
      state.radios = res.radios;
      state.checks = res.checks;
      state.inputs = res.inputs;
      state.stars = res.stars;
    });

    const result = {};
    const cacheResult = localStorage.getItem("QUESTION");
    const history = cacheResult ? JSON.parse(cacheResult) : {};
    const router = useRouter();
    const submit = () => {
      state.init = false; //点击提交按钮将该值置为false
      for (const key in state.validateResult) {
        if (!state.validateResult[key]) {
          return;
        }
      }
      const record = {
        user: store.state.userInfo.name,
        time: new Date().toLocaleString(),
        question: JSON.stringify(result),
      };
      const newId = api.saveHistory(record);
      router.push({
        name: "Success",
        params: {
          // 注意这里有原来的query改为了params
          id: newId,
        },
      });

      localStorage.removeItem("QUESTION");
    };
    const getValue = (val, title, flag, required) => {
      if (flag.indexOf("vote") >= 0) {
        let vote_result = `支持人数：${val.supValue}/${
          val.supValue + val.oppValue
        }；反对人数：${val.oppValue}/${val.supValue + val.oppValue}；支持率：${(
          (val.supValue / (val.supValue + val.oppValue || 1)) *
          100
        ).toFixed(2)}%`;
        result[flag] = `${title} >>> ${vote_result}`;
        state.validateResult[flag] = required
          ? val.supValue > 0 || val.oppValue > 0
          : true;
      } else {
        result[flag] = `${title} >>> ${val}`;
        //如果是必填则根据所选结果进行校验，否则直接更新为true表示校验通过
        state.validateResult[flag] = required ? !!("" + val).trim() : true;
      }
      history[flag] = val;
    };

    const save = () => {
      localStorage.setItem("QUESTION", JSON.stringify(history));
    };

    const recoveryResult = computed(() => {
      return function (title, flag, required) {
        state.validateResult[flag] = !required;
        if (history.hasOwnProperty(flag)) {
          getValue(history[flag], title, flag); //同时恢复已选结果result
        }

        return history.hasOwnProperty(flag) && history[flag];
      };
    });
    return {
      ...toRefs(state),
      submit,
      getValue,
      save,
      recoveryResult,
    };
  },
};
</script>

<style></style>
